package com.kld.shop.controller.admin;


import com.github.pagehelper.PageInfo;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.common.util.DateUtils;
import com.kld.promotion.po.Actorder;
import com.kld.shop.controller.base.BaseController;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.sys.api.ISysOrgUnitService;
import com.kld.promotion.api.IActOrderService;
import com.kld.sys.po.SysOrgUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 曹不正 on 2016/3/24.
 */

@Controller
@RequestMapping("/admin/actorder")
public class ActOrderController extends BaseController{
    
    @Autowired
    private IActOrderService actOrderService;
    @Autowired
    private ISysOrgUnitService sysOrgUnitService;

    @RequestMapping("/pointsDrawList")
    public String PointsDrawList(){
        return "admin/actorder/pointsDrawList";
    }

    @RequestMapping("/pointDrawDetailList")
    public String PointDrawDetailList(){
        return "admin/actorder/pointDrawDetailList";
    }
    /**
     * 积分抽奖订单
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getPointsDrawList")
    public ResultMsg GetPointsDrawList() throws UnsupportedEncodingException {
        Map<String,Object> map=new HashMap<String, Object>();
        //map.put("id", request.getParameter("id"));
        if(!getUserOuLevel().equals("1")){
            map.put("oucode",getUserOuCode());
        }
        String actTitle =  request.getParameter("actTitle");
        map.put("actTitle",actTitle);
        map.put("fromDate",request.getParameter("fromDate"));
        map.put("toDate",request.getParameter("toDate"));
        map.put("orderState",request.getParameter("orderState"));
        map.put("isWon", request.getParameter("isWon"));
        map.put("sort",request.getParameter("sort"));
        map.put("orderBy", request.getParameter("order"));
        PageInfo pageInfo = null;
        try {
            pageInfo = actOrderService.getPointsDrawList(map,getPageNum(),getPageSize());
        }catch (Exception e){
            logger.error("获取获奖名单列表错误"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    /**
     * 发奖功能
     * @param actorder
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/updateActOrderState",method = RequestMethod.POST)
    public ResultMsg UpdateActOrderState(Actorder actorder){
        ResultMsg result=new ResultMsg();
        actorder.setState(BigDecimal.valueOf(2));
        actorder.setDeliverytime(new Date());
        int i=actOrderService.updateByPrimaryKeySelective(actorder);
        if(i>0){
            result.setResult(true);
            result.setMsg("发奖成功");
        }else{
            result.setResult(true);
            result.setMsg("发奖失败");
        }
        return result;
    }

    @RequestMapping(value = "exportPointsDrawList",method = RequestMethod.GET)
    public void ExportPointsDrawList(){
        Map<String,Object> map=new HashMap<String, Object>();
        String actTitle =  request.getParameter("actTitle");
        if(!super.getUserOuLevel().equals(1)){
            map.put("oucode",super.getUserOuCode());
        }
        map.put("actTitle",actTitle);
        map.put("fromDate",request.getParameter("fromDate"));
        map.put("toDate",request.getParameter("toDate"));
        map.put("orderState",request.getParameter("orderState"));
        map.put("isWon", request.getParameter("isWon"));
        map.put("sort",request.getParameter("sort"));
        map.put("orderBy",request.getParameter("order"));
        List<Actorder> pointsDrawList =actOrderService.getPointsDrawList(map) ;
        String excelPath = "/resources/doctemplate/tpl_pointDrawOrder.xls";
        String root = request.getSession().getServletContext().getRealPath("/");
        String fileName = null;
        response.setCharacterEncoding("utf-8");
        try {
            response.setContentType("application/vnd.ms-excel; charset=ISO8859-1");
            InputStream is = new FileInputStream(root+excelPath);
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = sheet.getRow(2);
            HSSFCell cell = row.getCell(0);
            int flag = 0;
            for (Actorder ao:pointsDrawList){
                HSSFRow newRow = sheet.createRow(2 + flag);
                for(int j=0;j<17;j++){
                    newRow.createCell(j).setCellStyle(cell.getCellStyle());
                }
                newRow.getCell(0).setCellValue(ao.getActlogid().toString());
                newRow.getCell(1).setCellValue(ao.getPoints().toString());
                String actTypeName="";
                Integer actType=ao.getActtype().intValue();
                switch (actType){
                    case 1: actTypeName="月抽奖"; break;
                    case 2: actTypeName="积分抽奖"; break;
                    case 3: actTypeName="砸金蛋"; break;
                    default: actTypeName="";
                        break;
                }
                newRow.getCell(2).setCellValue(actTypeName);
                newRow.getCell(3).setCellValue(DateUtils.formatDate(ao.getCreatetime()));
                String iswonStr="";
                Integer iswon=ao.getIswon().intValue();
                switch (iswon){
                    case 0: iswonStr="未中奖"; break;
                    case 1: iswonStr="中奖"; break;
                    default: iswonStr="";
                        break;
                }
                newRow.getCell(4).setCellValue(iswonStr);
                newRow.getCell(5).setCellValue(ao.getPrizename());
                newRow.getCell(6).setCellValue(ao.getCardno());
                newRow.getCell(7).setCellValue(ao.getBelongareaname());
                newRow.getCell(8).setCellValue(ao.getPhone());
                newRow.getCell(9).setCellValue(ao.getUsername());
                newRow.getCell(10).setCellValue(ao.getTitle());
                String stateStr="";
                if(ao.getState()==null){
                    stateStr="已完成";
                }else {
                    Integer state = ao.getState().intValue();
                    switch (state) {
                        case -1:
                            stateStr = "未领奖";
                            break;
                        case 1:
                            stateStr = "待发奖";
                            break;
                        case 2:
                            stateStr = "已发奖";
                            break;
                        default:
                            stateStr = "";
                            break;
                    }
                }
                newRow.getCell(11).setCellValue(stateStr);
                newRow.getCell(12).setCellValue(ao.getExpress());
                newRow.getCell(13).setCellValue(ao.getDeliveryno());
                if(ao.getRealname()!=null&&!ao.getRealname().equals("")){
                    newRow.getCell(14).setCellValue(ao.getRealname());
                }
                String s=ao.getAreaname();
                newRow.getCell(15).setCellValue(s+ao.getAddress());
                if(ao.getZip()!=null&&!ao.getZip().trim().equals("")){
                    newRow.getCell(16).setCellValue(ao.getZip());
                }
                flag++;
            }
            fileName = new String(("积分抽奖订单").getBytes("gb2312"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    fileName + DateUtils.formatDate( DateUtils.getDate()) + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
            //poi 3.9 no close method
//            wb.close();
        }catch (Exception ex){
            String opname ="积分抽奖订单";
            BufferedOutputStream bos = null;
            logger.error("导出"+opname+"异常:"+ex.getMessage(),ex);
            try {
                response.setContentType("text/plain");
                fileName = new String((opname+"导出失败").getBytes("gb2312"), "ISO8859-1");
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                if(ex!=null){ buff =(ex.toString()+"==> 异常行号:"+ex.getStackTrace()[0].getLineNumber()).getBytes();}
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        fileName + DateUtils.formatDate(DateUtils.getDate()) + ".txt");
                bos.write(buff);
                bos.flush();
                if(bos!=null){ bos.close();}
            } catch (Exception e){
                logger.error("导出"+opname+"异常失败:"+e.getMessage(),e);
            }
        }

        return;
    }
    /**
     * 获取全部编码
     * @param code
     * @return
     */
    public List<String> getAllOuCode(String code){
        List<String> ncode=new ArrayList<String>();
        SysOrgUnit sysOrgunit=sysOrgUnitService.getSysOrgunitByOuCode(code);
        if(sysOrgunit!=null){
            if("1".equals(sysOrgunit.getOulevel().toString())){
                HashMap<String,Object> map=new HashMap<String, Object>();
                map.put("parentoucode",code);
                List<SysOrgUnit> sys_orgunits=sysOrgUnitService.getSysOrgunitList(map);
                for(SysOrgUnit s:sys_orgunits){
                    ncode.add(s.getOucode());
                }
            }else{
                ncode.add(code);
            }
        }
        return ncode;
    }
    @ResponseBody()
    @RequestMapping("getPointDrawDetailList")
    public ResultMsg getPointDrawDetailList(){
        Map<String,Object> map = new HashMap<String, Object>();
        String oucode = request.getParameter("oucode");
        String scycle = request.getParameter("scycle");
        String createDateFrom = request.getParameter("createDateFrom");
        String createDateTo = request.getParameter("createDateTo");
        String yy = request.getParameter("yy");
        String mm = request.getParameter("mm");
        String state= request.getParameter("state");
        if(StringUtils.isNotBlank(oucode)){
            map.put("oucode",getAllOuCode(oucode));
        }
        if(StringUtils.isNotBlank(scycle)){
            map.put("scycle",scycle);
            if("0".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
                map.put("createDateTo",createDateTo);
            }else if("1".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
            }else if("2".equals(scycle)){
                if(mm.length()==1){
                    mm="0"+mm;
                }
                map.put("yy",yy+"-"+mm);
            }else if("3".equals(scycle)){
                map.put("yy",yy);
            }
        }
        map.put("state",state);
        PageInfo pageInfo = null;
        try {
            pageInfo = actOrderService.getPointDrawDetailList(map,getPageNum(),getPageSize());
        }catch (Exception e){
            logger.error("获取获奖名单列表错误"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    @RequestMapping("exportPointDrawDetailList")
    public void exportPointDrawDetailList(){
        Map<String,Object> map = new HashMap<String, Object>();
        String oucode = request.getParameter("oucode");
        String scycle = request.getParameter("scycle");
        String createDateFrom = request.getParameter("createDateFrom");
        String createDateTo = request.getParameter("createDateTo");
        String yy = request.getParameter("yy");
        String mm = request.getParameter("mm");
        String state= request.getParameter("state");
        if(StringUtils.isNotBlank(oucode)){
            map.put("oucode",getAllOuCode(oucode));
        }
        if(StringUtils.isNotBlank(scycle)){
            map.put("scycle",scycle);
            if("0".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
                map.put("createDateTo",createDateTo);
            }else if("1".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
            }else if("2".equals(scycle)){
                if(mm.length()==1){
                    mm="0"+mm;
                }
                map.put("yy",yy+"-"+mm);
            }else if("3".equals(scycle)){
                map.put("yy",yy);
            }
        }
        map.put("state",state);
        List<Actorder> list =actOrderService.getPointDrawDetailList(map) ;
        String bedginDate = "";
        String endDate = "";
        if(StringUtils.isNotBlank(scycle)){
            map.put("scycle",scycle);
            if("0".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
                map.put("createDateTo",createDateTo);
                bedginDate = createDateFrom;
                endDate = createDateTo;
            }else if("1".equals(scycle)){
                map.put("createDateFrom",createDateFrom);
                bedginDate = createDateFrom;
                endDate = createDateFrom;
            }else if("2".equals(scycle)){
                if(mm.length()==1){
                    mm="0"+mm;
                }
                map.put("yy", yy + "-" + mm);
                bedginDate = yy+"-"+mm+"-01";
                endDate = yy+"-"+mm+"-"+ymd(yy,mm);
            }else if("3".equals(scycle)){
                map.put("yy",yy);
                bedginDate = yy+"-01-01";
                endDate = yy+"-12-30";
            }
        }
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = sFormat.format(new Date());
        String excelPath = "/resources/doctemplate/tpl_pointDrawDetailReport.xls";
        String root = request.getSession().getServletContext().getRealPath("/");
        String fileName = null;
        response.setCharacterEncoding("utf-8");
        try {
            response.setContentType("application/vnd.ms-excel; charset=ISO8859-1");
            InputStream is = new FileInputStream(root+excelPath);
            HSSFWorkbook wb = new HSSFWorkbook(is);
            HSSFSheet sheet = wb.getSheetAt(0);

            HSSFRow row_2=sheet.getRow(1);
            HSSFCell cell_1_3=row_2.getCell(2);
            cell_1_3.setCellValue((String)request.getSession().getAttribute("ouname"));

            HSSFCell cell_1_5=row_2.getCell(5);
            cell_1_5.setCellValue(bedginDate);

            HSSFCell cell_1_8=row_2.getCell(8);
            cell_1_8.setCellValue(endDate);

            HSSFCell cell_1_11=row_2.getCell(11);
            cell_1_11.setCellValue(dateStr);

            HSSFRow row = sheet.getRow(3);
            HSSFCell cell = row.getCell(0);
            int flag = 0;
            for (Actorder ao:list){
                HSSFRow newRow = sheet.createRow(3 + flag);
                for(int j=0;j<13;j++){
                    newRow.createCell(j).setCellStyle(cell.getCellStyle());
                }
                newRow.getCell(0).setCellValue(ao.getActlogid().toString());
                newRow.getCell(1).setCellValue(ao.getStrcreatetime());
                newRow.getCell(2).setCellValue("小积分抽大奖");
                newRow.getCell(3).setCellValue(ao.getPoints().toString());
                newRow.getCell(4).setCellValue(ao.getPrizename());
                newRow.getCell(5).setCellValue(ao.getSelfprice());
                String stateStr="";
                if(ao.getState().intValue()==2){
                    stateStr="是";
                }else{
                    stateStr="否";
                }
                newRow.getCell(6).setCellValue(stateStr);
                newRow.getCell(7).setCellValue(ao.getRealname());
                newRow.getCell(8).setCellValue(ao.getPhone());
                newRow.getCell(9).setCellValue(ao.getCardno());
                newRow.getCell(10).setCellValue(ao.getAreaname());
                newRow.getCell(11).setCellValue(ao.getAddress());
                newRow.getCell(12).setCellValue(ao.getZip());
                flag++;
            }
            HSSFCellStyle styleFoot = wb.createCellStyle(); // 样式对象
            styleFoot.setVerticalAlignment(HSSFCellStyle.ALIGN_FILL);// 垂直
            styleFoot.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 水平
            Font fontFoot = wb.createFont();
            fontFoot.setFontHeightInPoints((short) 10);   //--->设置字体大小
            fontFoot.setFontName("微软雅黑");   //---》设置字体，是什么类型例如：宋体
            styleFoot.setFont(fontFoot);     //--->将字体格式加入到styleTitle中
            styleFoot.setWrapText(true);
            HSSFRow rowLast = sheet.createRow(3 + flag);
            sheet.addMergedRegion(new Region(3 + flag, (short) 0, 3 + flag, (short) 12));
            rowLast.setHeightInPoints(40);
            HSSFCell cellFoot = rowLast.createCell((short) 0);
            cellFoot.setCellStyle(styleFoot);
            cellFoot.setCellValue("制表人：____________  复审人: ____________  审核人: ____________");

            fileName = new String(("积分商城中奖明细").getBytes("gb2312"), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    fileName + DateUtils.formatDate(DateUtils.getDate()) + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
            //poi 3.9
//            wb.close();
        }catch (IOException ex){

            String opname ="积分商城中奖明细";
            BufferedOutputStream bos = null;
            logger.error("导出"+opname+"异常:"+ex.getMessage(),ex);
            try {
                response.setContentType("text/plain");
                fileName = new String((opname+"导出失败").getBytes("gb2312"), "ISO8859-1");
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                if(ex!=null){ buff =(ex.toString()+"==> 异常行号:"+ex.getStackTrace()[0].getLineNumber()).getBytes();}
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        fileName + DateUtils.formatDate(DateUtils.getDate()) + ".txt");
                bos.write(buff);
                bos.flush();
                if(bos!=null){ bos.close();}
            } catch (Exception e){
                logger.error("导出"+opname+"异常失败:"+e.getMessage(),e);
            }


        }
    }

    public static String ymd(String y,String m){
        String d="";
        int yy = Integer.valueOf(y);
        if((yy % 4 ==0 && yy % 100!=0) || yy % 400 ==0) {
            if(m=="2") {d="29";} else if(m=="4" || m=="6"|| m=="9" || m=="11") {d="30";} else {d="31";}
        }else {
            if(m=="2") {d="28";} else if(m=="4" || m=="6"|| m=="9" || m=="11") {d="30";} else {d="31";}
        }
        return d;
    }

}
